package cn.swufe.edu.stu.hw_tools.Time;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import cn.swufe.edu.stu.hw_tools.R;

public class TomatoTimeActivity extends AppCompatActivity {

    private TextView textViewTime;
    private TextView textViewCountdown;
    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tomato_time);

        textViewTime = findViewById(R.id.textViewTime);
        textViewCountdown = findViewById(R.id.CountTimer);

        ImageView imageView = findViewById(R.id.tmtimageView1);
        // 获取Drawable并转换为AnimationDrawable
        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
        // 开始播放动画
        animationDrawable.start();

        // 初始化倒计时为25分钟
        long timeLeft = 25 * 60 * 1000; // 25分钟转换为毫秒
        countDownTimer = new CountDownTimer(timeLeft, 200) { // 200毫秒更新一次
            @Override
            public void onTick(long millisUntilFinished) {
                // 更新倒计时显示
                int minutes = (int) (millisUntilFinished / 60000);
                int seconds = (int) ((millisUntilFinished % 60000) / 1000);
                textViewCountdown.setText(String.format("倒计时25分钟，当前剩余:\n\n%02d:%02d", minutes, seconds));
            }

            @Override
            public void onFinish() {
                // 倒计时结束
                textViewCountdown.setText("00:00");
                // 这里可以添加倒计时结束后需要执行的代码
                Toast.makeText(TomatoTimeActivity.this, "╲(｡◕‿◕｡)╱游戏！启动！╲(｡◕‿◕｡)╱", Toast.LENGTH_SHORT).show();
            }
        }.start();

        // 更新当前时间，200毫秒刷新一次
        Handler timeHandler = new Handler();
        timeHandler.post(new Runnable() {
            @Override
            public void run() {
                // 更新时间显示
                updateTime();
                // 递归地调度自己，每200毫秒执行一次
                timeHandler.postDelayed(this, 200);
            }
        });
    }
    private void updateTime() {
        // 获取当前时间并格式化为HH:mm:ss格式
        String timeString = String.format("当前时间为:\n\n%tH:%tM:%tS", System.currentTimeMillis(), System.currentTimeMillis(), System.currentTimeMillis());
        textViewTime.setText(timeString);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消倒计时和时间更新
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    public void back(View btn){
        Intent intent = getIntent();
        setResult(2,intent);
        finish();
    }

}